#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: categories.py
@contact: zwb15083976291@163.com
@time: 2021/11/10
"""
from django.utils.decorators import method_decorator

from admin.serializers.categories import CategoriesSerializer, PostCategoriesSerializer, PutCategoriesSerializer, \
    DeleteCategoriesSerializer, BatchDeleteCategoriesSerializer
from common.models import BlogCategorie
from utils.filters.views_filters import SearchCategoriesFilter
from utils.responses import CommonAPIResponseStatus, CommonResponse
from utils.serializers.serializer import PaginatorSerializer
from utils.user_authentication import allow_admin_user
from utils.views import BasePaginateGenericAPIView
import logging

logger = logging.getLogger("default")


@method_decorator(allow_admin_user, name='dispatch')
class ManagementCategoriesView(BasePaginateGenericAPIView):
    diff_methods_serializer_class = dict(get=PaginatorSerializer, post=PostCategoriesSerializer,
                                         put=PutCategoriesSerializer, delete=DeleteCategoriesSerializer)
    diff_methods_request_params = dict(
        get=dict(optional=['pageNum', 'pageSize', 'search'], defualt_value=dict(pageNum=1, pageSize=10)),
        post=dict(required=["categorie_name"]),
        put=dict(required=["id", "categorie_name"]),
        delete=dict(required=["id"])

    )

    filter_backends = [SearchCategoriesFilter]

    def get(self, request):
        ret, message = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=message)
        query_set = self.filter_queryset(queryset=BlogCategorie.objects.order_by('-create_time'))
        paginator, models = self.paginate_queryset(query_set, self.serializer.validated_data)
        # 创建文章接口提供
        sear_data = dict(instance=models, many=True)
        if request.query_params.get("article", False):
            sear_data["serial_fields"] = ["id", "categorie_name"]
        # 文章列表搜索提供
        elif request.query_params.get("articlelist", False):
            sear_data["serial_fields"] = ["id", "categorie_name"]
            return CommonResponse(data=CategoriesSerializer(**sear_data).data)
        return CommonResponse(data=self.get_paginated_response(self.serializer.validated_data, paginator,
                                                               CategoriesSerializer(**sear_data).data))

    def post(self, request):
        ret, message = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=message)
        self.serializer.save()
        return CommonResponse(message="创建分类成功", data=self.serializer.data)

    def put(self, request):
        ret, message = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=message)
        self.serializer.select_field_update_obj()
        return CommonResponse(message="修改分类成功", data=self.serializer.data)

    def delete(self, request):
        ret, message = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=message)
        self.serializer.select_field_delete_obj()
        return CommonResponse(message="删除分类成功", data=self.serializer.data)


@method_decorator(allow_admin_user, name='dispatch')
class BatchManagementCategoriesView(BasePaginateGenericAPIView):
    diff_methods_serializer_class = dict(delete=BatchDeleteCategoriesSerializer)
    diff_methods_request_params = dict(delete=dict(required=["ids"]))

    def delete(self, request):
        ret, message = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=message)
        categories = BlogCategorie.objects.filter(id__in=set(self.query_data['ids']))
        data = CategoriesSerializer(serial_fields=["id", "categorie_name"], instance=categories, many=True).data
        categories.delete()
        return CommonResponse(message="批量删除成功", data=data)
